package com.example.wist.mediaplayer;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

/**
 * Created by wist on 5/21/2016.
 */
public class MusicService extends Service implements Runnable,
        MediaPlayer.OnCompletionListener,
        MediaPlayer.OnErrorListener{

    final int CURRENT_PLAY_TIME = 0x123;
    public static MediaPlayer mMusicPlayer = null;
    int musicState = 0;//播放音乐状态

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //注册接收器
        ActivityReceiver receiver=new ActivityReceiver();
        IntentFilter filter=new IntentFilter();
        filter.addAction(AppContant.PlayerMSG.MUSICSERVICE_ACTION);
        registerReceiver(receiver, filter);

        mMusicPlayer = new MediaPlayer();
        /* 监听播放是否完成 */
        mMusicPlayer.setOnCompletionListener(this);
        /* 调用m.reset()时可能有错 */
        mMusicPlayer.setOnErrorListener(this);
    }

    @Override
    public void onCompletion(MediaPlayer mp) {

        ++MainActivity.musicPosition;
        MainActivity.musicPosition %= MainActivity.musicNum;
        int i = MainActivity.musicPosition;

        Log.e("tag","+++++++++++complete+++++++++++"+i);
        playMusic(MainActivity.musicUri[i]);
        MainActivity.music.setText(MainActivity.musicTitle[i]);
        MainActivity.singer.setText(MainActivity.artist[i]);
    }

    @Override
    public boolean onError(MediaPlayer mediaPlayer, int what, int extra){

        Log.i("tag","this is a error");
        return true;
    }

    //处理run()
    Handler playHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int what = msg.what;

            switch (what) {
                case CURRENT_PLAY_TIME:
                    Bundle bundle = msg.getData();
                    String mTime = bundle.getString("mTime");
                    MainActivity.currentMTime.setText(mTime);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mMusicPlayer != null) {
            mMusicPlayer.reset();
            mMusicPlayer.release();
            mMusicPlayer = null;
        }
        System.out.println("service is destroy");
    }
/* service 接收参数方法 */
//    @Override
//    public int onStartCommand(Intent intent, int flags, int startId) {
//
//        /* 得到startService传来的动作，后面是默认参数，这参数是我自定义的常量 */
//        MSG = intent.getIntExtra("MSG", AppContant.PlayerMSG.PLAY_CLICK);
//        currentPosition = intent.getIntExtra("position", 0);
//
//        int mResourse;
//
//        switch (MSG) {
//            /* 传进来的是切歌事件 */
//            case AppContant.PlayerMSG.PLAY_CLICK:
//                playMusic(MainActivity.musicUri[currentPosition]);
//                //设置播放按钮为播放
//                mResourse = R.drawable.img_button_notification_play_pause_grey;
//                MainActivity.startPause.setBackground(getResources().getDrawable(mResourse));
//                break;
//
//            //传进来的是暂停事件
//            case AppContant.PlayerMSG.PAUSE:
//
//                if (mMusicPlayer.isPlaying()) {//正在播放
//                    mMusicPlayer.pause();//暂停
//                    //设置播放按钮为播放
//                    Log.e("tag", "mMusicPlayer.pause();");
//                    mResourse = R.drawable.img_button_notification_play_play_grey;
//                } else {
//                    mMusicPlayer.start();
//                    //设置播放按钮为暂停
//                    Log.e("tag", "mMusicPlayer.start();");
//                    mResourse = R.drawable.img_button_notification_play_pause_grey;
//                }
//                MainActivity.startPause.setBackground(getResources().getDrawable(mResourse));
//
//                break;
//
//        }
//        return super.onStartCommand(intent, flags, startId);
//    }

    //接收Activity传来的数据和控制消息
    class ActivityReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent){
            String musicPath = intent.getStringExtra("musicPath");
            int controlInfo  = intent.getIntExtra("controlInfo", -1);
            Log.e("tag",musicPath);

            switch (controlInfo) {
                /* 传进来的是播放事件 */
                case AppContant.PlayerMSG.MUSIC_PLAY:
                    if(musicState == AppContant.PlayerMSG.MUSIC_PAUSE)//service没有放音乐
                        mMusicPlayer.start();
                    else
                        playMusic(musicPath);

                    musicState = AppContant.PlayerMSG.MUSIC_PLAY;
                    break;

                /* 传进来的是暂停事件 */
                case AppContant.PlayerMSG.MUSIC_PAUSE:
                    if (mMusicPlayer.isPlaying()) {//正在播放
                        mMusicPlayer.pause();
                        musicState = AppContant.PlayerMSG.MUSIC_PAUSE;
                    }
                    break;

                default:
                    Log.e("tag","the operation is illegal.");

            }
        }
    }
    //切歌
    public void playMusic(String musicPath) {

        try {
            //重置
            mMusicPlayer.reset();
            mMusicPlayer.setDataSource(musicPath);
            //准备播放
            mMusicPlayer.prepare();
//            mMusicPlayer.prepareAsync();
            //播放
            mMusicPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mMusicPlayer.start();
                    /* 获得歌曲的总时间并显示 */
                    String mTime = turnToMinute(MusicService.mMusicPlayer.getDuration() / 1000);
                    MainActivity.totalMTime.setText(mTime);
                }
            });

            //Log.e("tag", "play music service============");
            //进度条清零
            MainActivity.musicSeekBar.setMax(MusicService.mMusicPlayer.getDuration());

            int position = MainActivity.musicPosition;
            MainActivity.music.setText(MainActivity.musicTitle[position]);
            MainActivity.singer.setText(MainActivity.artist[position]);
            //Log.e("tag", "++++++++" + MusicService.mMusicPlayer.getDuration());
            new Thread(this).start();
        } catch (Exception ex) {
            Log.e("tag", "service播放失败");
            Log.e("tag", ex.getMessage());
        }
    }

    /* 将毫秒->时间格式00：00 */
    private String turnToMinute(int second) {

        int minute = second / 60;
        int sec = second % 60;
        String time = "";
        if (minute >= 10) {
            time = minute + ":";
        } else {
            time = "0" + minute + ":";
        }
        if (sec >= 10) {
            time = time + sec;
        } else {
            time = time + "0" + sec;
        }
        return time;
    }

    //线程控制进度条
    @Override
    public void run() {

        //注意此处用的是毫秒
        int curPosition = 0;
        int total = mMusicPlayer.getDuration();
        while (mMusicPlayer != null && curPosition < total) {
            try {

                Thread.sleep(1000);
                if (mMusicPlayer != null) {
                    //获取毫秒数
                    curPosition = mMusicPlayer.getCurrentPosition();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            MainActivity.musicSeekBar.setProgress(curPosition);
            String mTime = turnToMinute(curPosition/1000);
            //Log.e("tag","curPosition=="+curPosition);
            Bundle bundle = new Bundle();
            Message message = playHandler.obtainMessage();
            bundle.putString("mTime",mTime);
            message.setData(bundle);
            message.what = CURRENT_PLAY_TIME;
            playHandler.sendMessage(message);
        }
    }

}
